﻿/* Write a program that replaces all occurrences of the substring "start" with the substring "finish" in a text file. Ensure it will work with large files (e.g. 100 MB). */

using System;
using System.IO;
using System.Text.RegularExpressions;

namespace _7.ReplaceAllOccurrences
{
    class ReplaceAllOccurrences
    {
        static void Main()
        {
            /*** tested with a 100MB text file, works on decent speed ***/
            Console.Write("Path to input file: ");
            string path_to_input_file = Console.ReadLine();
            string fileContents;
            string replace_pat = "start", replace_str = "finish"; //replace pattern and replace string
            try
            {
                StreamReader SR = new StreamReader(@path_to_input_file);
                using (SR)
                {
                    fileContents = SR.ReadToEnd();
                }
            }
            catch (FileNotFoundException fn)
            {
                throw new FileNotFoundException("File not found, " + fn.Message);
            }
            catch (OverflowException oe)
            {
                throw new OverflowException("Stack overflow, may be the file is too big?, " + oe.Message);
            }
            catch (IOException ioe)
            {
                throw new IOException("Error: the input file could not be read, " + ioe.Message);
            }
            //replace occurences ignoring the substring lower/upper case
            fileContents = Regex.Replace(fileContents, replace_pat, replace_str, RegexOptions.IgnoreCase);

            try
            {
                StreamWriter SW = new StreamWriter(@path_to_input_file, false);
                using (SW)
                {
                    SW.Write(fileContents);
                }
            }
            catch (OverflowException oe)
            {
                throw new OverflowException("Stack overflow, may be the file is too big?, " + oe.Message);
            }
            catch (IOException ioe)
            {
                throw new IOException("Error: the input file could not be read, " + ioe.Message);
            }
            Console.WriteLine("New data: \r\n{0}", fileContents);
            Console.WriteLine("Data succesfully written to " + path_to_input_file);
        }
    }
}
